<template>
  <vx-card class="pt-5" full>
    <div class="userSearchTop">
      <div class="userSearch">
        <vs-input
          label="视图名称"
          size="small"
          icon="icon-search"
          icon-pack="feather"
          icon-after="true"
          class="inputx no-icon-border "
          v-model="searchList.viewName"
          @blur="getViewList()"
        />
      </div>
      <vs-button
        color="primary"
        icon="icon-plus"
        icon-pack="feather"
        @click="handleAdd"
        size="small"
      >新增</vs-button>
    </div>
    <vx-table
      :data="tableData"
      :total="recordsTotal"
      :pageSize="pageSize"
      @current-change="currentChange"
      class="mt-4"
    >
      <el-table-column prop="viewName" label="视图名称" sortable minwidth="100"></el-table-column>
      <el-table-column prop="status" minwidth="500" label="适用组织">
        <template slot-scope="scope" align="center">
          <span v-for="(item,index) in scope.row.deptResponses" :key="index">{{item.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <feather-icon
            title="编辑"
            icon="EditIcon"
            :svgClasses="['stoke-current text-primary w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleEdit(scope.$index, scope.row)"
          />
          <feather-icon
            title="配置"
            icon="SlidersIcon"
            :svgClasses="['stoke-current text-primary w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleSet(scope.$index, scope.row)"
          />
          <feather-icon
            title="删除"
            icon="Trash2Icon"
            :svgClasses="['stoke-current text-danger w-5 h-5']"
            class="cursor-pointer p-2"
            @click.stop="handleDelete(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </vx-table>
    <!--新增-编辑 模态框开始 -->
    <vx-popup
      classContent="popup-example"
      :title="popTitle"
      :active.sync="popupActivoAdd"
      :isValid="handleIsValidate"
      @confirmPopup="addUser"
      @cancelPopup="popupActivoAdd = false;"
    >
      <div class="addPopcontent">
        <div class="pr-1">
          <vs-input
            label="视图名称："
            class="inputx mt-2 red"
            v-model="popList.viewName"
            name="登录名"
            data-vv-validate-on="input|blur"
            v-validate="'required|min:3'"
          />
          
          <span style="color:red">*</span><span class="text-sm pl-2" style="margin-left:-4px">所属桥梁：</span>
          <el-input v-model="checkedDepartName" readonly="readonly" class="ml-1">
            <el-button class="chooseBtn" v-if="chooseDepart" slot="append" @click="switchDepart">选择</el-button>
            <el-button class="closeBtn" v-else slot="append" @click="switchDepart">关闭</el-button>
          </el-input>
        </div>
      </div>
      <!-- 所属部门 -->
      <div class="vx-card departContainer" v-show="!chooseDepart">
        <h4 class="pl-3">部门选择</h4>
        <VuePerfectScrollbar class="mt-5 scroll-area">
          <tree-component
            ref="tree"
            node-key="id"
            :data="treeData"
            @check="getCheckedKeys"
            :render-content="renderContent"
            show-checkbox
            default-expand-all
          ></tree-component>
        </VuePerfectScrollbar>
      </div>
    </vx-popup>
    <!-- 新增-编辑 模态框结束 -->

    <!--配置 模态框开始 -->
    <vx-popup
      classContent="popup-example"
      title
      :active.sync="popupEditVisible"
      :isValid="popupVisible"
      @confirmPopup="setViews"
      @cancelPopup="popupEditVisible = false;"
      class="vs-popup"
    >
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first"> </el-tab-pane>
      <el-tab-pane label="菜单信息" name="second"></el-tab-pane>
      <el-tab-pane label="自定义信息" name="third"></el-tab-pane>
    </el-tabs>
<view-set :name='activeName' :rowInfo='rowInfo' ref="viewSetPage" ></view-set>
     
    </vx-popup>
    <!-- 配置 模态框结束 -->

    <!--删除模态框开始 -->
    <vx-popup
      classContent="popup-example"
      title="删除"
      :active.sync="popupActivoDel"
      :isValid="true"
      width="400px"
      @confirmPopup="delData"
      @cancelPopup="popupActivoDel = false"
    >
      <span>确定删除这条数据吗？</span>
    </vx-popup>
    <!-- 删除模态框结束 -->
  </vx-card>
</template>
<script>
import VuePerfectScrollbar from "vue-perfect-scrollbar";
import TreeComponent from "@/components/model-tree/ModelTree.vue";
import ViewSet from "./ViewSet";
import base from "@/api/base"; // 导入接口域名列表
import md5 from "js-md5";
export default {
  props: ["image", "clearList"],
  data() {
    return {
      activeName: "second",
      rowInfo: {},
      treeData: [],
      popTitle: "新增",
      searchList: {
        viewName: ""
      },
      selectRowId: "",
      tableData: [],
      popupVisible: false,
      popupEditVisible: false,
      popList: {
        viewName: "",
        userViewId: "",
        deptId: [],
        depName: []
      },
      checkedDepartName: "",
      popupActivoAdd: false,
      popupActivoPassword: false,
      popupActivoDel: false,
      chooseDepart: true,
      isEditor: false,
      recordsTotal: 0,
      currentPage: 1,
      pageSize: 7
    };
  },
  methods: {
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    //树名称显示
    renderContent(h, { node }) {
      let iconSkin;
      if (node.data.type == 5) {
        iconSkin = "icon-department";
      } else if (node.data.type == 3) {
        iconSkin = "icon-center";
      } else if (node.data.type == 4) {
        iconSkin = "icon-site";
      } else {
        iconSkin = "icon-group";
      }
      return (
        <span class="custom-tree-node flex items-center">
          <i class={`othericon ${iconSkin}`} />
          <span style="margin-left:5px;">{node.data.name}</span>
        </span>
      );
    },
    //获取部门树
    getDepartData() {
      this.$api.accessControl
        .departmentTree()
        .then(res => {
          this.setDepDisable( res.data.data)
          this.treeData = res.data.data;
          // this.addDisabled(this.treeData)
        })
        .catch();
    },
    setDepDisable(data){
      let arr = []
      data.forEach((item,index)=>{
        if(item.type == '5')
        arr.push(index)
      
      })
      for(let i = arr.length-1;i>=0;i--){
        data.splice(arr[i],1)
      }
      console.log(arr)
      console.log(data)
      data.forEach(item=>{
        if(item.children)
        this.setDepDisable(item.children)
      })
    },
    addDisabled(data){
      data.forEach(item=>{
        if(item.type != 4){
          item.disabled = true
        }else{
          item.disabled = false
        }
        if(item.children)
        this.addDisabled(item.children)
      })
    },
    //部门树-选择
    getCheckedKeys() {
      let oldDepartName = this.$refs.tree.$refs.tree.getCheckedNodes();
      if(oldDepartName.length>=2){
        let arr = []
        oldDepartName.forEach((item,index)=>{
          if(item.type != '4')
          arr.push(index)
        })
        for(let i = arr.length-1;i>=0;i--){
        oldDepartName.splice(arr[i],1)
        }
      } 
      if(oldDepartName && oldDepartName.length){
        let arr1 = []
        oldDepartName.forEach((item,index,arr)=>{
          if(item.id == this.popList.deptId[0])
          arr1.push(index)
        })
        for(let i = arr1.length-1;i>=0;i--){
        oldDepartName.splice(arr1[i],1)
        }
      }
      if(!oldDepartName[0]){
        this.$refs.tree.$refs.tree.setCheckedKeys([]);
        this.checkedDepartName ='';
        this.popList.deptId = []
      }else{
        this.$refs.tree.$refs.tree.setCheckedKeys([oldDepartName[0].id]);
        this.checkedDepartName = oldDepartName[0].name;
        this.popList.deptId = [oldDepartName[0].id]
      }
        


    },
    changeTree(val) {
      let arr = [];
      if (val && val.length !== 0) {
        val.forEach(item => {
          let obj = {};
          obj.name = item.name;
          if (item.children && item.children.length >= 1) {
            obj.children = this.changeTree(item.children);
          }
          arr.push(obj.name);
        });
      }

      return arr;
    },
    //分页
    currentChange(currentPage) {
      this.currentPage = currentPage * this.pageSize - this.pageSize;
      this.getViewList(currentPage * this.pageSize - this.pageSize);
    },
    //表格行新增
    handleAdd() {
      this.popTitle = "新增";
      this.isEditor = false;
      Object.keys(this.popList).forEach(v => {
        this.popList[v] = "";
      });
      this.checkedDepartName = "";
      this.popupActivoAdd = true;
      this.$validator.reset();
     
      this.$refs.tree.$refs.tree.setCheckedKeys([]);
    },
    addUser() {
      // if(this.popList.viewName)
      // console.log(this.popList.viewName.split(''))
      if(this.popList.viewName.split('').length>=15){
        this.$vs.notify({ text: "视图名称长度超限", color: "danger" });
        return ;
      }
      if (this.popTitle == "编辑") {
        let params = {
          viewName: this.popList.viewName,
          sysDeptIds: this.popList.deptId,
          userViewId: this.popList.userViewId
        };
        this.$api.accessControl.editView(params).then(res => {
          console.log(res);
          if (res.status == 200) {
            this.$vs.notify({ text: "修改成功", color: "success" });
            this.getViewList(this.currentPage);
          }
        });
      } else {
        let params = {
          viewName: this.popList.viewName,
          sysDeptIds: this.popList.deptId
        };
        this.$api.accessControl.addView(params).then(res => {
          console.log(res);
          if (res.status == 200) {
            this.$vs.notify({ text: "添加成功", color: "success" });
            this.getViewList(this.currentPage);
          }
        });
      }
      this.popupActivoAdd = false;
    },
    //表格行编辑
    handleEdit(index, row) {
      this.popList.viewName = row.viewName;
      this.popList.userViewId = row.userViewId;
      this.popList.deptId = [];
      this.checkedDepartName = "";
      let oldDepartName = [];
      if (row.deptResponses) {
        row.deptResponses.forEach(v => {
          this.popList.deptId.push(v.deptId);
          oldDepartName.push(v.name);
        });
        this.$refs.tree.$refs.tree.setCheckedKeys(this.popList.deptId);
        this.checkedDepartName = oldDepartName.join(",");
      }
        // this.setdisabled()

      this.popTitle = "编辑";
      this.popupActivoAdd = true;
      this.isEditor = true;
    },
    setViews() {
      console.log("确定");
      let params = this.$refs.viewSetPage.getParams();
      this.$api.accessControl.saveViewConfig(params).then(res => {
        console.log(res);
        if (res.status == 200) {
          this.$vs.notify({ text: "修改成功", color: "success" });
          this.popupEditVisible = false;
          this.getViewList(this.currentPage);
        } else this.$vs.notify({ text: "修改失败", color: "danger" });
      });
    },
    //视图-配置
    handleSet(index, row) {
      this.rowInfo = row;
      this.popupVisible = true;
      this.popupEditVisible = true;
      console.log(index);
      console.log(row);
    },
    //表格行删除
    handleDelete(delIndex, delRow) {
      this.popupActivoDel = true;
      this.selectRowId = delRow.userViewId;
    },
    delData() {
      this.$api.accessControl
        .delView(this.selectRowId)
        .then(res => {
          if (res.data.success) {
            this.$vs.notify({ text: "删除成功", color: "danger" });
            this.getViewList((this.currentPage = 1));
          } else {
            this.$vs.notify({ text: "删除失败", color: "danger" });
          }
        })
        .catch(() => {});
      this.popupActivoDel = false;
    },
    //用户筛选
    getViewList(startPage) {
      let params = {
        start: startPage || 0,
        length: this.pageSize,
        viewName: this.searchList.viewName
      };
      this.$api.accessControl
        .viewsList(params)
        .then(res => {
          this.tableData = res.data.data;
          this.recordsTotal = res.data.recordsTotal;
        })
        .catch(() => {});
    },
    //部门选择框
    switchDepart() {
      this.chooseDepart = !this.chooseDepart;
      if(!this.chooseDepart){
        this.getDepartData();
      }
    }
  },
  watch: {
    popupActivoAdd() {
      this.popupActivoAdd ? "" : (this.chooseDepart = true);
    },
    image(value) {
      this.file = value;
    },
    clearList() {
      this.file = "";
    },
    file(value) {
      const list = value;
      this.$emit("update:image", list);
    }
  },
  computed: {
    handleIsValidate() {
      return (
        !this.errorBags.any() &&
        this.popList.realname != "" &&
        this.popList.username != "" &&
        this.popList.mobile != ""
      );
    }
  },
  components: {
    VuePerfectScrollbar,
    TreeComponent,
    ViewSet
  },
  created() {
    this.getViewList();
  },
  mounted() {
    
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/baseColor.scss";
@import "~@/assets/fonts/other-icon/iconfont.css";

/deep/.vs-input--input.normal {
  font-size: 11.9px;
}
.userSearchTop {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .vs-component.vs-con-input-label.vs-input {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 22rem;
    /deep/ .vs-input--label {
      margin-right: 0.8rem;
    }
    /deep/ .vs-inputx.vs-input--input.hasIcon.icon-after-input {
      padding: 0.7rem 1rem !important;
    }
  }
}
.userSearch {
  position: relative;
}
.addUserBtn {
  color: #fff;
  background: $mainColor;
}
.saveAddData {
  float: right;
}
.addPopcontent {
  display: flex;
  justify-content: space-between;
  > div {
    width: 50%;
    .con-select,
    .vs-input {
      width: 98% !important;
      margin: 0 auto;
    }
  }
}
.editPassword {
  .con-select,
  .vs-input {
    width: 100% !important;
  }
}

@media screen and (max-width: 1920px) {
  .departContainer {
    // border-radius: 0 2% 2% 0;
    width: 20%;
    position: absolute;
    right: calc(27% - 245px);
    top: 24%;
    height: 56.5%;
    z-index: 1;
    .pl-3 {
      margin-top: 15px;
      // margin-left:20px;
    }
  }
}
// @media screen and (max-width: 1366px) {
//   .departContainer {
//     border-radius: 0 2% 2% 0;
//     width: 250px;
//     position: absolute;
//     right: calc(30% - 280px);
//     top: 20%;
//     height: 65%;
//     z-index: 1;
//   }
// }
/deep/.el-input__inner:focus {
  border-color: $mainColor;
}
/deep/.el-input__inner {
  // background-color: #dcdfe6;
}
/deep/.el-input-group__append,
.el-input-group__prepend {
  background-color: transparent;
  border-color: transparent;
}
.chooseBtn {
  padding-top: 1.1rem;
  font-size: 0.85rem;
  color: #fff !important;
  background-color: $mainColor;
}
.closeBtn {
  padding-top: 1.1rem;
  font-size: 0.85rem;
  color: #fff !important;
  background-color: #f56c6c !important;
}
.scroll-area {
  height: calc(var(--vh, 1vh) * 100 - 27.9rem);
  /deep/ .el-icon-folder-opened:before {
    content: "" !important;
  }
}
.el-upload-list--picture-card .el-upload-list__item,
/deep/.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.el-icon-upload-success.el-icon-check {
  position: relative;
  top: -35px;
}
.email {
  display: block;
}
/deep/ i.othericon {
  color: $mainColor;
  font-size: 18px;
}

  /deep/.vs-popup{
    width:650px;
  }
</style>
